<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="代码" prop="code"><el-input v-model="queryParams.code" placeholder="请输入代码" clearable @keyup.enter.native="handleQuery" /></el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['binance:kConf:add']">新增</el-button></el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['binance:kConf:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5"><el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['binance:kConf:export']">导出</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="confList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="代码" align="center" prop="code" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleChart(scope.row)" v-hasPermi="['binance:monitoring:chart']">分析</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['binance:kConf:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改K线关注对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="代码" prop="code"><el-input v-model="form.code" placeholder="请输入代码" /></el-form-item>
        <el-form-item label="备注" prop="remark"><el-input v-model="form.remark" type="textarea" placeholder="请输入内容" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 折线图 -->
    <el-dialog :title="selectCode" :visible.sync="chartOpen" width="80%" append-to-body>
      <el-date-picker
        v-model="timeArr"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        :default-time="['00:00:00', '23:59:59']"
        value-format="yyyy-MM-dd HH:mm:ss"
        @change="initChart"
        style="margin: 20px 120px 0"
      ></el-date-picker>
      <div id="echarts_box" style="width: 100%; height: 450px"></div>
      <div id="echarts_macd" style="width: 100%; height: 200px"></div>
    </el-dialog>
  </div>
</template>

<script>
import { listConf, getConf, delConf, addConf, updateConf } from '@/api/binance/kConf';
import { selectChart, selectMacd15 } from '@/api/binance/monitoring';
import * as echarts from 'echarts';

export default {
  name: 'kConf',
  data() {
    return {
      chartOpen: false,
      timeArr: [], //开始时间和结束时间数组
      startTime: null,
      endTime: null,
      selectCode: null,
      handleType: 1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // K线关注表格数据
      confList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleChart(row) {
      this.chartOpen = true;
      this.selectCode = row.code;
      let time = new Date().getTime() + 900 * 1000;
      let endTime = time - 24 * 3600 * 1000;
      this.startTime = this.parseTime(endTime);
      this.endTime = this.parseTime(time);
      this.initChart();
    },
    initChart() {
      let params = {
        code: this.selectCode,
        startTime: this.timeArr[0] || this.startTime,
        endTime: this.timeArr[1] || this.endTime
      };
      selectChart(params).then(res => {
        if (res.code == 200) {
          const pictureData = res.data;

          // 折线图渲染开始
          let myChart = echarts.init(document.getElementById('echarts_box'), 'macarons');
          let option = {
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: ['分时线(元)', '15分均价(元)', '30分均价(元)', '时均价(元)', '日均价(元)', '15分-日算术均价(元)']
            },
            toolbox: {
              show: false,
              feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            calculable: true,
            xAxis: [
              {
                type: 'category',
                boundaryGap: false,
                data: pictureData.map(item => {
                  return item.time;
                }),
                axisLabel: {
                  show: true,
                  textStyle: {
                    color: '#333'
                  }
                }
              }
            ],
            yAxis: [
              {
                type: 'value',
                min: function(value) {
                  return value.min * 0.998; // 最小值 = 数据最小值 × 90%
                },
                max: function(value) {
                  return value.max * 1.002; // 最大值 = 数据最大值 × 120%
                },
                //interval: 0.02, // 固定刻度间隔
                // splitNumber: 10, // 尝试分段
                axisLabel: {
                  show: true,
                  textStyle: {
                    color: '#333'
                  }
                }
              }
            ],
            series: [
              {
                name: '分时线(元)',
                type: 'line',
                data: pictureData.map(item => {
                  return item.close;
                }),
                markPoint: {
                  data: [{ type: 'max', name: '最大值' }, { type: 'min', name: '最小值' }]
                },
                itemStyle: {
                  normal: {
                    color: '#70bbff'
                  }
                }
              },
              {
                name: '15分均价(元)',
                type: 'line',
                data: pictureData.map(item => {
                  return item.min15;
                }),
                markPoint: {},
                itemStyle: {
                  normal: {
                    color: '#ffaa00'
                  }
                }
              },
              {
                name: '30分均价(元)',
                type: 'line',
                data: pictureData.map(item => {
                  return item.min30;
                }),
                markPoint: {},
                itemStyle: {
                  normal: {
                    color: '#fff25d'
                  }
                }
              },
              {
                name: '时均价(元)',
                type: 'line',
                data: pictureData.map(item => {
                  return item.hour;
                }),
                markPoint: {},
                itemStyle: {
                  normal: {
                    color: '#000000'
                  }
                }
              },
              {
                name: '日均价(元)',
                type: 'line',
                data: pictureData.map(item => {
                  return item.price;
                }),
                markPoint: {},
                itemStyle: {
                  normal: {
                    color: '#ff0000'
                  }
                }
              },
              ,
              {
                name: '15分-日算术均价(元)',
                type: 'line',
                data: pictureData.map(item => {
                  return item.min15_day;
                }),
                markPoint: {},
                itemStyle: {
                  normal: {
                    color: '#0000ff'
                  }
                }
              }
            ]
          };
          myChart.setOption(option);
        } else {
          // this.$message.error(res.data.msg);
        }
      });

      selectMacd15(params).then(res => {
        if (res.code == 200) {
          const pictureData = res.data;

          // 折线图渲染开始
          let myMacd = echarts.init(document.getElementById('echarts_macd'), 'macarons');
          let option = {
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: ['15分MACD']
            },
            toolbox: {
              show: false,
              feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                restore: { show: true },
                saveAsImage: { show: true }
              }
            },
            calculable: true,
            xAxis: [
              {
                type: 'category',
                boundaryGap: false,
                data: pictureData.map(item => {
                  return item.time;
                }),
                axisLabel: {
                  show: true,
                  textStyle: {
                    color: '#333'
                  }
                }
              }
            ],
            yAxis: [
              {
                type: 'value',
                min: function(value) {
                  return value.min * 0.998; // 最小值 = 数据最小值 × 90%
                },
                max: function(value) {
                  return value.max * 1.002; // 最大值 = 数据最大值 × 120%
                },
                //interval: 0.02, // 固定刻度间隔
                // splitNumber: 10, // 尝试分段
                axisLabel: {
                  show: true,
                  textStyle: {
                    color: '#333'
                  }
                }
              }
            ],
            series: [
              {
                name: '15分MACD',
                type: 'line',
                data: pictureData.map(item => {
                  return item.bar;
                }),
                markPoint: {},
                itemStyle: {
                  normal: {
                    color: '#ffaa00'
                  }
                }
              }
            ]
          };
          myMacd.setOption(option);
        } else {
          // this.$message.error(res.data.msg);
        }
      });
    },
    /** 查询K线关注列表 */
    getList() {
      this.loading = true;
      listConf(this.queryParams).then(response => {
        this.confList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        code: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.code);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.handleType = 1;
      this.reset();
      this.open = true;
      this.title = '添加K线关注';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.handleType = 2;
      this.reset();
      const code = row.code || this.ids;
      getConf(code).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改K线关注';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.handleType == 2) {
            updateConf(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addConf(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const codes = row.code || this.ids;
      this.$modal
        .confirm('是否确认删除K线关注编号为"' + codes + '"的数据项？')
        .then(function() {
          return delConf(codes);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'binance/conf/export',
        {
          ...this.queryParams
        },
        `conf_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
